package com.zs4sdk.activity.login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.common.library.data.CommonEventHandler;
import com.common.library.data.CommonHandle;
import com.common.library.data.EventHandler2Get;
import com.common.library.util.ActivityHelper;
import com.common.library.util.HandlerUtil;
import com.common.library.util.Helper;
import com.common.library.util.NetworkHelper;
import com.common.library.util.ParamsHelper;
import com.zs4gamesdk.R;
import com.zs4sdk.common.Extra;
import com.zs4sdk.dialog.Zs4GameTipDialog;
import com.zs4sdk.entity.AutoLoginJSONResultEntity;
import com.zs4sdk.entity.LoginJSONResultEntity;
import com.zs4sdk.entity.Zs4GameData;
import com.zs4sdk.statistics.Zs4GameStatistics;

import org.apache.http.NameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by Administrator on 2018/4/17.
 */

 class Zs4GameSelectLoginProxy extends Zs4GameLoginProxyBase implements View.OnClickListener {

    private ImageView imgLoginByPhone;
    private ImageView imgFastLogin;
    protected View imgZs4GameBack;
    protected View linSelectLoginLayout;
    int GET_GUEST = 101;//获取游客账号
    int FIRST_LOGIN = 102;//注册成功判断为第一次登陆
    int GET_IDLOGIN = 103;//ID登录
    int PHONE_TYPE1 = 2;//手机号属于未注册
    int PHONE_TYPE2 = 3;//手机号已注册但没有设置密码
    int PHONE_TYPE3 = 4;//手机号已注册已设置密码
    public static final String LOGINTYPE_EMAIL = "EMAIL";
    public static final String LOGINTYPE_EXCHANGE = "EXCHANGE";
    private MyZs4GameTipDialog mMyZs4GameTipDialog;
    public Zs4GameSelectLoginProxy(Activity act,View v){
        super(act,v);
        imgLoginByPhone = (ImageView) mMainView.findViewById(R.id.imgZs4GameStartByPhone);
        imgFastLogin = (ImageView) mMainView.findViewById(R.id.imgZs4GameStartFast);
        linSelectLoginLayout = mMainView.findViewById(R.id.linSelectLoginLayout);
        imgZs4GameBack = mMainView.findViewById(R.id.img_zs4_game_back);
        imgFastLogin.setOnClickListener(this);
        imgLoginByPhone.setOnClickListener(this);
        imgZs4GameBack.setOnClickListener(this);
        init();
        linSelectLoginLayout.setVisibility(View.VISIBLE);
       // doCheckLogin();
    }

    protected void init(){
        mZs4GameOtherAccountLogin = new Zs4GameSelectLoginAndRegist(mActivity,mMainView,myHandle);
        mZs4GameLoginInputPhone = new Zs4GameLoginInputPhone(mActivity,mMainView,myHandle);
        mZs4GameOtherAccountLogin.setOnClickListener(this);
        mZs4GameLoginInputPhone.setOnClickListener(this);
    }

    protected void doStartByPhone(){
        linSelectLoginLayout.setVisibility(View.GONE);
        imgZs4GameBack.setVisibility(View.VISIBLE);
        mZs4GameLoginInputPhone.showLogin();
        loginStyle = INPUT_PHONE;
    }
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if(id == R.id.imgZs4GameStartFast){
           if(mMyZs4GameTipDialog == null){
               mMyZs4GameTipDialog = new MyZs4GameTipDialog(mActivity);
           }
           mMyZs4GameTipDialog.showDialog();
        }else if(id == R.id.imgZs4GameStartByPhone){
            doStartByPhone();
        }else if(id == R.id.btn_zs4game_next){
            if(mZs4GameLoginInputPhone.isCanDoNext()){
               mZs4GameLoginInputPhone.login();
            }
        }else if(id == R.id.img_zs4_game_back){
            onBackPressed();
        }else if(id == R.id.zs4gameviewid_btn_login_with_verifycode){
            mZs4GameOtherAccountLogin.login();
        }
    }
    /**
     * 检测
     */
    private void doCheckLogin() {
        if (NetworkHelper.isNetworkAvailable(mActivity)) {
            HandlerUtil.sendMessage(myHandle, Extra.MessageKey.SHOWPROCESS);
            ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();
            String url =    Extra.URL.GUESTREGISTERURL;
            url =    Extra.URL.CHECKLOGIN;
            new EventHandler2Get(
                    url,//USER_REGIESTER_ACCOUUNT GUESTREGISTERURL
                    paramList,
                    ParamsHelper.getUserAgent1(),
                    new CommonEventHandler.ResultHandlerInEvent() {

                        @Override
                        public void doResultHanler(JSONObject result) throws JSONException {
                            HandlerUtil.sendMessage(myHandle, Extra.MessageKey.DISMISSPROCESS);
                            Message msg = myHandle.obtainMessage();
                            msg.what = Extra.MessageKey.CHECK_LOGIN;
                            msg.obj = result;
                            msg.arg1 = Extra.MessageKey.REQUEST_REGISTER_GUEST_SUCCESS;
                            // 发送消息

                            Bundle bundle = new Bundle();
                            msg.setData(bundle);
                            myHandle.sendMessage(msg);
                        }

                        @Override
                        public void doExceptionHandler() {
                            HandlerUtil.sendMessage(myHandle, Extra.MessageKey.DISMISSPROCESS);
                        }
                    });
        } else {
        }

    }

    /**
     * 自动登录
     */
    private void doRequestRegisterGuest() {
        if (NetworkHelper.isNetworkAvailable(mActivity)) {
            HandlerUtil.sendMessage(myHandle, Extra.MessageKey.SHOWPROCESS);
            ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();
            String url =    Extra.URL.GUESTREGISTERURL;
            url =    Extra.URL.AUTO_LOGIN;
            new EventHandler2Get(
                    url,//USER_REGIESTER_ACCOUUNT GUESTREGISTERURL
                    paramList,
                    ParamsHelper.getUserAgent1(),
                    new CommonEventHandler.ResultHandlerInEvent() {
                        @Override
                        public void doResultHanler(JSONObject result) throws JSONException {
                            Log.e("auto"," autoLogin result is "+result.toString());
                            HandlerUtil.sendMessage(myHandle, Extra.MessageKey.DISMISSPROCESS);
                            Message msg = myHandle.obtainMessage();

                            msg.what = Extra.MessageKey.REQUEST_SUCCESS;
                            msg.obj = result;
                            msg.arg1 = Extra.MessageKey.REQUEST_REGISTER_GUEST_SUCCESS;
                            // 发送消息

                            Bundle bundle = new Bundle();
                            bundle.putString("param2",result.getString("nickname"));
                            msg.setData(bundle);
                            myHandle.sendMessage(msg);
                        }

                        @Override
                        public void doExceptionHandler() {
                            HandlerUtil.sendMessage(myHandle, Extra.MessageKey.DISMISSPROCESS);
                        }
                    });
        } else {
        }

    }

    CommonHandle myHandle = new CommonHandle(mActivity, new CommonHandle.HandleMessage() {

        @Override
        public void doHandleMessage(Message msg) {
            if(Extra.MessageKey.CHECK_LOGIN == msg.what){
                JSONObject jsonObject1 = (JSONObject) msg.obj;
                LoginJSONResultEntity entity = null;
                entity = new AutoLoginJSONResultEntity(jsonObject1);
                boolean isSwitchAccount = Zs4GameData.getInstance().saveUserLoginInfoForLoginedSuccess(entity);
                if(Helper.isNotNull(entity) && entity.isSuccess()){
                    Intent intent = new Intent();
                    intent.setClass(mActivity,Zs4GameLoginActivity.class);
                    mActivity.startActivity(intent);
                    mActivity.finish();
                }else{
                   // linSelectLoginLayout.setVisibility(View.VISIBLE);
                }
                return;
            } else if(Extra.MessageKey.REQUESTCOMPLETE_LASTLOGINACCOUNT == msg.what){

            }else if (Extra.MessageKey.REQUEST_SUCCESS == msg.what) {
                String type = "";
                String account = "";
                String password = "";
                Bundle bundle = msg.getData();
                if (Helper.isNotNull(bundle.containsKey("str"))) {
                    if (bundle.containsKey("param1")) {
                        type = bundle.getString("param1");
                    }
                    if (bundle.containsKey("param2")) {
                        account = bundle.getString("param2");
                    }
                    if (bundle.containsKey("param3")) {
                        password = bundle.getString("param3");
                    }
                }
                JSONObject jsonObject1 = (JSONObject) msg.obj;
                Zs4GameLoginBase.loginSuccess(mActivity,type,jsonObject1,account,password);
             //   String deviceId = ReYunTracking.getDeviceId();
                String userId = jsonObject1.optString(LoginJSONResultEntity.COLUMN_USERID);
                Log.e("use"," userId is "+userId);
                Zs4GameStatistics.setRegisterWithAccountID(userId);
            }else if(msg.what == Extra.MessageKey.VERIFY_PHONE_REGIDTER_OR_LOGIN){
                gotoPhoneLogin(msg.arg1);
            }
        }
    });

    public void onBackPressed(){
        switch (loginStyle){
            case TOURIST_LOGIN:
                break;
            case INPUT_PHONE:
                loginStyle = TOURIST_LOGIN;
                imgZs4GameBack.setVisibility(View.GONE);
                linSelectLoginLayout.setVisibility(View.VISIBLE);
                mZs4GameLoginInputPhone.hideLogin();
                break;
            case PHONE_LOGIN:
                mZs4GameLoginInputPhone.showLogin();
                mZs4GameOtherAccountLogin.hideLogin();
                loginStyle = INPUT_PHONE;
                break;
        }
    }
    protected void gotoPhoneLogin1(int style){
         if(style == Zs4GameLoginInputPhone.NO_REGIST){
            mZs4GameLoginInputPhone.hideLogin();
            mZs4GameOtherAccountLogin.showLogin();
            String phoneNumber = (String)mZs4GameLoginInputPhone.getData();
            mZs4GameOtherAccountLogin.setData(phoneNumber);
            loginStyle = PHONE_LOGIN;
         }else if(style == Zs4GameLoginInputPhone.REGIST_NO_PASSWORD){
             ActivityHelper.showLongToast(mActivity,mActivity.getString(R.string.zs4game_phone_regist));
         }else if(style == Zs4GameLoginInputPhone.REGIST_SET_PASSOWRD){
             ActivityHelper.showLongToast(mActivity,mActivity.getString(R.string.zs4game_phone_regist));
         }else{
            ActivityHelper.showLongToast(mActivity,mActivity.getString(R.string.zs4game_input_right_phone));
         }
    }

    private class MyZs4GameTipDialog extends Zs4GameTipDialog {

        public MyZs4GameTipDialog(@NonNull Context context) {
            super(context);
        }
        public void startGame(){
            doRequestRegisterGuest();
            closeDialog();
        }
    }
}
